<?php

namespace App\Services;

use App\Http\Controllers\AesController as Aesss;
use App\Models\User;
use App\Models\VerificationCode;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class DriverLoginService extends BaseService
{
    /**
     * @param string $phone
     * @param string $password
     * @param string $type
     * @return array
     * @throws \App\Exceptions\BobException
     * 登录
     */
    public function login(array $data)
    {
        $user = User::query()->where('phone', $data['phone'])->first();
        $type = 1; //默认已设置密码
        if ($data['type'] == 1) {
            $code_info = VerificationCode::query()->where('channel', 'sms')->where('account', $data['phone'])->orderByDesc('created_at')->first();
            if (!$code_info || $code_info->state == 1 || $code_info->code != $data['code']) {
                return_bobc('验证码有误');
            }
            $code_info->state = 1;
            $code_info->save(); //更新状态
            $code_info->delete(); //删除
            if (!$user) {
                $user = $this->user_add($data);
                $type = 0; //未设置密码
            }
        } else {
            if (!$user) return_bobc('该用户不存在');
            if (!password_verify($data['password'], $user->password)) {
                return_bobc('密码不正确,请重新输入');
            }
            $type = 1;
        }
        //清除token
        self::del_token($user);
        return $this->respondWithToken($user, $type);
    }

    protected function del_token(User $user)
    {
        if ($user != null) {
            DB::table('oauth_access_tokens')->where('user_id', $user->id)->delete();
        }
    }

    /**
     * @param array $data
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|null|object
     * 注册时新增
     */
    public function user_add(array $data)
    {
        $user = new User();
        $user->phone = $data['phone'];
        $user->balance = 0;
        $user->company_id = 1;
        $user->save();
        $user = User::query()->where('id', $user->id)->first();
        return $user;
    }

    /**
     * @param User $user
     * @return array
     */
    public function respondWithToken(User $user, $type): array
    {
        // 直接创建token并设置有效期
        $token = Aesss::encrypt($user->id);
        $user->token = $token;
        $user->save();
        $createToken = $user->createToken($user->password);
        $createToken->token->expires_at = Carbon::now()->addDays(30);
        $createToken->token->save();
        return [
            'token' => $createToken->accessToken,
            'token_type' => "Bearer",
            'expires_in' => Carbon::now()->addDays(30),
            'type' => $type,
            'u_token' => $token,
        ];
    }
}